<template>
  <view>
    <view class="bg-set"></view>
    <view class="profile">
      <!-- 头部 -->
      <view class="title">
        <view style="margin-bottom: 20rpx;">欢迎光临</view>
        <view>联勤保障部队第906医院</view>
      </view>
      <!-- 主体 -->
      <view class="content">
        <uni-forms :value="infoForm.userinfo" :rules="rules" ref="formsRef">
          <!-- 姓名 -->
          <uni-forms-item name="customerName">
            <view class="name">
              <view><text class="icon icon-yonghu-xianxing"></text></view>
              <view class="txt">用户</view>
              <input v-model="infoForm.userinfo.customerName" placeholder="请输入您的姓名/昵称" type="nickname"
                @blur="getNickname">
            </view>
          </uni-forms-item>
          <!-- 电话 -->
          <uni-forms-item name="phoneNumber">
            <view class="name">
              <view><text class="icon icon-dianhua-copy"></text></view>
              <view class="txt">电话</view>
              <input type="number" v-model="infoForm.userinfo.phoneNumber" placeholder="请输入您的手机号">
            </view>
          </uni-forms-item>
          <!-- 地址 -->
          <uni-forms-item>
            <view class="name">
              <view><text class="icon icon-dingwei"></text></view>
              <view class="txt">地址</view>
              <input type="text" :value="store.profile?.addressTxt" disabled style="width: 500rpx;" />
            </view>
          </uni-forms-item>
        </uni-forms>
        <!-- 敬老模式 -->
        <!-- <view style="margin: 20rpx 0;">请选择使用方式</view>
        <view class="mode">
          <view class="mode_btn" v-for="(item, index) in modeBtn" :key="index" @click="activeindex = index"
            :class="{ active: activeindex === index }">
            <icon :class="'iconfont ' + item.icon" style="font-size: 50rpx;"></icon>

            <text>{{ item.txt }}</text>
          </view>
        </view> -->
        <button class="button" @click="onConfirm" type="submit" :loading="loading">确认</button>
      </view>
      <!-- 底部 -->
      <view class="footer" :style="{ marginBottom: safeAreaInsets?.bottom + 'px' }">该版权归玮炜信息所有</view>
    </view>
  </view>
</template>

<script setup>
import { ref, watch } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { useMemberStore } from '../../stores';
import { http } from '../../utils/http';
import { reactive } from 'vue';
const { safeAreaInsets } = uni.getSystemInfoSync()
const store = useMemberStore()
//获取用户昵称
const getNickname = (e) => {
  infoForm.userinfo.customerName = e.detail.value
}
const flag = ref('false')
const loading = ref(false)//确认按钮loading效果
onLoad(async (e) => {
  // 动态设置导航栏标题
  flag.value = e.id ? true : false
  uni.setNavigationBarTitle({
    title: flag.value ? '编辑信息' : '登录'
  });
  // 编辑页面||之前有登陆过登录页面实现数据回显
  if (flag.value || store.profile?.customerName) {
    const { customerName, phoneNumber, addressTxt } = store.profile
    infoForm.userinfo = { ...infoForm.userinfo, customerName, phoneNumber, addressTxt }
  }
  // 获取登录凭证code
  const { code } = await uni.login()
  await getOppid(code)
  // 解析二维码动态参数，获取扫码地址的id
  if (e.q) {
    const store = useMemberStore()
    const str = decodeURIComponent(e.q)
    const regex = /address_id=([^&]+)/;
    const match = str.match(regex);
    if (match) {
      // 解析二维码地址
      const addressId = match[1];
      const requestAddressObj = { data: { addressId }, ...store.requestData }
      const { data, errcode, errmsg } = await http({
        method: 'post',
        url: '/GetAddressById',
        data: requestAddressObj
      })
      if (errcode == 99990) {
        return uni.showToast({ title: errmsg, icon: 'none' })
      }
      const address = data[0].addressName + data[0].subaddress1[0]?.addressName + ' ' + data[0].subaddress1[0]?.subaddress2[0]?.addressName
    
      const addressSerials = data[0].subaddress1[0]?.subaddress2[0]?.addressSerials
      //地址保存致仓库，并同时更新表单数据
      store.profile = { addressTxt: address, addressId, addressSerials }
      infoForm.userinfo.addressTxt = address
      infoForm.userinfo.addressId = addressId
    }
  }
  // 判断用户是否之前登录过，并且不是再编辑页面下，获取用户信息，并直接跳转首页
  if (store.requestData.openId && !flag.value) {
    GetCustomersInfo()
  }
})
const formsRef = ref()//表单实例
// 用户信息表单校验对象
let infoForm = reactive({
  userinfo: {
    customerName: '',
    phoneNumber: '',
    addressTxt: '',
    openId: "",//
    sessionKey: "",
    addressId: '',
  }

})
// 用户信息提交数据库-请求数据
let infoData = (
  {
    reqtime: "",
    reqdatapage: "",
    pagedatanum: "",
    openId: "",
    sessionKey: "",
    customerId: "",
    data: {
      customerinfo: {
        customerId: "",
        status: "",
        customerName: "",
        nickName: "",
        avataUrl: "",
        phoneNumber: "",
        customerTypeCode: "",
        sex: "",
        birthday: "",
        idNo: "",
        hisId: "",
        hisKey: "",
        openId: "",
        loginCode: "",
        unionId: "",
        sessionKey: "",
        customerClassSerials: "",
        customerClassCode: "",
        customerClassName: "",
        addressId: ""
      }
    }
  })
// 表单校验
const rules = {
  customerName: {
    rules: [{ required: true, errorMessage: '姓名不能为空' }]
  },
  phoneNumber: {
    rules: [
      { required: true, errorMessage: '手机号不能为空' },
      { pattern: /^1[3-9]\d{9}$/, errorMessage: '手机号格式不正确' }
    ]
  }
}
// 获取用户oppid
const getOppid = async (code) => {
  const { openid, session_key } = await http({
    url: `/GetOpenid?code=${code}`
  })
  infoForm.userinfo.openId = openid
  infoForm.userinfo.sessionKey = session_key
  store.requestData.openId = infoForm.userinfo.openId
  store.requestData.customerId = infoForm.userinfo.openId
  store.requestData.sessionKey = infoForm.userinfo.sessionKey
}
// 获取用户信息
const GetCustomersInfo = async () => {
  const store = useMemberStore()
  const res = await http({
    method: 'post',
    url: '/GetCustomersInfo',
    data: store.requestData
  })
  //  将获取到的用户信息存储仓库并直接跳转首页
  if (res.data?.length > 0) {
    // 在登录页面获取用户信息，更新用户信息将最新地址发送给后台，主要是为了后续可能统计用户换地址的历史记录todo
    if(!flag.value){
      if (res.data[0]?.addressList.length > 0) {
      if (res.data[0]?.addressList.filter(item => item.status == '1')) {
        watch([() => infoForm.userinfo.addressId], (newval, oldval) => {
       
          infoForm.userinfo.addressId=newval[0]
}, { deep: true, immediate: true })
console.log(infoForm.userinfo.addressId,'侦听修改最新的值');
        await http({
          method: 'post',
          url: '/UpdateCustomersInfo',
          data: {
            ...store.requestData,
            data: {
              "customerId": store.requestData.customerId,
              "openId": store.requestData.openId,
              "customerName": '',
              "nickName": "",
              "avataUrl": "",
              "phoneNumber":'',
              "sex": "",
              "birthday": "",
              "idNo": "",
              "hisId": "",
              "addressId":infoForm.userinfo.addressId
            }
          }
        })
      }
    }
    }
 
    store.profile = { ...store.profile, ...res.data[0] }
    uni.switchTab({ url: '/pages/home/home' })
  }
}
// 点击确认
const onConfirm = async () => {
  await formsRef.value.validate()//表单校验
  // 新增用户信息
  if (!flag.value) {
    const store = useMemberStore()
    if (!store.profile?.openId) {
      const { addressTxt, addressId, ...form } = infoForm.userinfo
      store.profile.addressTxt = addressTxt
      infoData.customerId = form.openId
      infoData.data.customerinfo.customerId = form.openId
      infoData.data.customerinfo.addressId = addressId
      infoData = { ...infoData, ...form }
      infoData.data.customerinfo = { ...infoData.data.customerinfo, ...form }
      //解构相同的请求数据存储致仓库
      const { customerName, data, phoneNumber, ...reqData } = infoData
      store.profile = { ...store.profile, customerName, phoneNumber }
      store.requestData = { ...store.requestData, ...reqData }
      // 新增用户信息
      await http({
        url: '/AddNewCustomersInfo',
        method: 'post',
        data: infoData
      })
      // 更新用户信息
      await http({
          method: 'post',
          url: '/UpdateCustomersInfo',
          data: {
            ...store.requestData,
            data: {
              "customerId": store.requestData.customerId,
              "openId": store.requestData.openId,
              "customerName": '',
              "nickName": "",
              "avataUrl": "",
              "phoneNumber": '',
              "sex": "",
              "birthday": "",
              "idNo": "",
              "hisId": "",
              "addressId":infoForm.userinfo.addressId
            }
          }
        })
    }
  } else {
    if (loading.value) return uni.showToast({ title: '请勿重复操作', icon: 'none' })
    loading.value = true
    // 编辑用户信息
    let { customerName, phoneNumber } = infoForm.userinfo
    // 监听表单数据是否有更新，并重新赋值
    watch([() => infoForm.userinfo.customerName, () => infoForm.userinfo.phoneNumber], (newval, oldval) => {

      customerName = newval[0],
        phoneNumber = newval[1]
    }, { deep: true, immediate: true })

    const { openId, sessionKey } = store.requestData
    const { addressId } = store.profile
    infoData.data.customerinfo.addressId = addressId
    infoData.data.customerinfo = { ...infoData.data.customerinfo, customerName, phoneNumber }
    const requestUpdateObj = { ...store.requestData, data: { ...infoData.data.customerinfo, openId, sessionKey, customerId: openId, } }
    await http({
      url: '/UpdateCustomersInfo',
      method: 'post',
      data: requestUpdateObj
    })
    loading.value = false
    // 用户信息更新之后同时更新pinia仓库 
    store.profile.customerName = customerName
    store.profile.phoneNumber = phoneNumber
    store.profile = { ...store.profile, customerName, phoneNumber }
  }
  uni.showToast({ title: flag.value ? '信息已修改' : '注册成功', icon: 'success' })
  setTimeout(() => {
    uni.switchTab({ url: '/pages/home/home' })
  }, 200)
}


const modeBtn = [{ icon: 'iconyanjing', txt: '普通模式' }, { icon: 'iconyanjing1', txt: '敬老模式' }]
const activeindex = ref(0)


</script>


<style scoped lang="scss">
::v-deep .uni-forms-item {
  margin-bottom: 0;
}

::v-deep .input-value-border {
  border: 0;
}

.profile {
  height: 130rpx;
  padding: 40rpx 0;
  border-radius: 0 0 40rpx 50rpx;
  background-color: #0081ff;

}

.bg-set {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-color: #f4f4f4;
  z-index: -1;
}

.title {
  width: 100%;
  height: 100rpx;
  margin-top: 50rpx;
  box-sizing: border-box;
  text-align: center;
  color: #fff;
  font-weight: 700;
}

.content {
  margin: 20rpx;
  border-radius: 12rpx;
  padding: 20rpx 10rpx;
  background-color: #fff;
  box-shadow: 0rpx 30rpx 20rpx -30rpx #acacac;

  .name {
    display: flex;
    align-items: center;
    height: 80rpx;
    width: 100%;
    border-bottom: 2rpx solid #eee;

    .txt {
      min-width: 50rpx;
      margin: 0 20rpx 0 5rpx;
    }
  }
}

.mode {
  display: flex;
  width: 100%;
  justify-content: space-around;

  .mode_btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 250rpx;
    // background-color: #eee;
    border-radius: 50rpx;
  }
}

.active {
  color: #fff;
  background-color: #2979ff;
}

.button {
  width: 100%;
  color: #fff;
  margin-top: 20rpx;
  background-color: #2979ff;
}

.footer {
  position: fixed;
  bottom: 0;
  font-size: 25rpx;
  color: #787474;
  left: 50%;
  transform: translate(-50%);
}
</style>